import { unref } from 'vue';

import { useUserStore } from '@/store/modules/user';

import { useProjectSetting } from '@/hooks/setting/useProjectSetting';

export function usePermission() {
  const userStore = useUserStore();

  /**
   * 检查权限
   * @param accesses
   */
  function _somePermissions(accesses: string[]) {
    const { getPermissionCheck } = useProjectSetting();

    const permissionCheck = unref(getPermissionCheck);

    return [...userStore.getPermissions, ...userStore.getPowers].some((item: any) => {
      // const { value }: any = item;
      return permissionCheck ? accesses.includes(item) : true;
    });
  }

  /**
   * 判断是否存在权限
   * 可用于 v-if 显示逻辑
   * */
  function hasPermission(accesses: string[]): boolean {
    const { getPermissionCheck } = useProjectSetting();

    const permissionCheck = unref(getPermissionCheck);

    if (!accesses || !accesses.length) return true;
    return permissionCheck ? _somePermissions(accesses) : true;
  }

  /**
   * 是否包含指定的所有权限
   * @param accesses
   */
  function hasEveryPermission(accesses: string[]): boolean {
    const permissionsList = [...userStore.getPermissions, ...userStore.getPowers];

    const { getPermissionCheck } = useProjectSetting();

    const permissionCheck = unref(getPermissionCheck);

    if (Array.isArray(accesses)) {
      return permissionCheck
        ? permissionsList.every((access: any) => accesses.includes(access))
        : true;
    }
    throw new Error(`[hasEveryPermission]: ${accesses} should be a array !`);
  }

  /**
   * 是否包含其中某个权限
   * @param accesses
   * @param accessMap
   */
  function hasSomePermission(accesses: string[]): boolean {
    const permissionsList = [...userStore.getPermissions, ...userStore.getPowers];

    const { getPermissionCheck } = useProjectSetting();

    const permissionCheck = unref(getPermissionCheck);

    if (Array.isArray(accesses)) {
      return permissionCheck
        ? permissionsList.some((access: any) => accesses.includes(access))
        : true;
    }
    throw new Error(`[hasSomePermission]: ${accesses} should be a array !`);
  }

  return { hasPermission, hasEveryPermission, hasSomePermission };
}
